export default class YouDao{
	public static appKey = "8zgyD3xVvBUHf46ioCEMy3vSyMa04H12"
	public static all = new Map()
	public static locale = uni.getLocale()
	public static locales = {
		'zh_Hans': 'zh-CHS',
		'zh_Hant': 'zh-CHT',
		'en': 'en',
		'ja': 'ja',
		'ko': 'ko'
	}
	
	public static translate(obj:any, key:string){
		const strMap = YouDao.all.get(obj[key])
		if(!strMap){
			YouDao.http(obj[key]).then((res)=>{
				console.log(res)
			})
		}else{
			const str = strMap.get(YouDao.locale)
			if(!str){
				YouDao.http(obj[key]).then((res)=>{
					console.log(res)
				})
			}
		}
	}
	
	private static http(query: string){
		const salt = (new Date()).getTime()
		const curtime = Math.round(new Date().getTime()/1000)
		return new Promise((resolve)=>{
			uni.request({
				url: "https://openapi.youdao.com/api",
				method: 'POST',
				data: {
					q: query,
					appKey: YouDao.appKey,
					salt,
					from: 'auto',
					to: YouDao.locales[YouDao.locale],
					sign: YouDao.appKey + YouDao.truncate(query) + salt + curtime,
					signType: "v3",
					curtime,
					vocabId: '1d68be95656f8b2f',
				},success: (res) => {
					console.log(res)
					resolve(res)
				}
			})
		})
	}
	
	private static truncate(q){
	    var len = q.length;
	    if(len<=20) return q;
	    return q.substring(0, 10) + len + q.substring(len-10, len);
	}
}